package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.clients.ItemClient;
import com.hmall.common.clients.UserClient;
import com.hmall.common.pojo.Address;
import com.hmall.common.pojo.Item;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.service.IOrderService;
import com.hmall.order.web.AuthorizationInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private UserClient userClient;
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long submitOrder(Integer num, Integer paymentType, Integer addressId, Integer itemId) {
        //获取用户id
        String userId = AuthorizationInterceptor.getUserId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }

        // Step 1: 查询商品信息
        Item item = itemClient.findById(itemId);
        if (item == null) {
            throw new RuntimeException("商品不存在");
        }
        // Step 2: 计算商品总价
        Long totalFee = item.getPrice() * num;
        // Step 3: 查询用户收货地址
        Address address=    userClient.findAddressById(Long.valueOf(addressId));
        if (address == null) {
            throw new RuntimeException("收货地址不存在");
        }

        // Step 4: 创建Order对象并插入到tb_order表
        Order order = new Order();
        order.setTotalFee(totalFee);
        order.setPaymentType(paymentType);
        order.setUserId(Long.valueOf(userId));
        order.setStatus(1); // 1为未付款
        orderMapper.insert(order);

        // Step 5: 创建OrderDetail对象并插入到tb_order_detail表
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(order.getId());
        orderDetail.setItemId(Long.valueOf(itemId));
        orderDetail.setNum(num);
        orderDetail.setName(item.getName());
        orderDetail.setPrice(item.getPrice());
        orderDetail.setSpec(item.getSpec());
        orderDetail.setImage(item.getImage());
        orderDetailMapper.insert(orderDetail);

        // Step 6: 创建OrderLogistics对象并插入到tb_order_logistics表
        OrderLogistics orderLogistics = new OrderLogistics();
        orderLogistics.setOrderId(order.getId());
        orderLogistics.setContact(address.getContact());
        orderLogistics.setMobile(address.getMobile());
        orderLogistics.setProvince(address.getProvince());
        orderLogistics.setCity(address.getCity());
        orderLogistics.setTown(address.getTown());
        orderLogistics.setStreet(address.getStreet());
        orderLogisticsMapper.insert(orderLogistics);

        // Step 7: 扣减库存
        itemClient.deStock(Long.valueOf(itemId), num);

        return order.getId();
    }

    /**
     * 检查并取消超时未支付的订单
     */
    @Transactional(rollbackFor = Exception.class)
    public void cancelTimeoutOrders() {
        // Step 1: 查询超时未支付的订单
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1) // 1 表示未支付状态
                .lt("create_time", new Date(System.currentTimeMillis() - 30 * 60 * 1000)); // 超过30分钟

        List<Order> timeoutOrders = orderMapper.selectList(queryWrapper);

        if (timeoutOrders.isEmpty()) {
            log.info("没有超时未支付的订单");
            return;
        }

        // Step 2: 遍历订单，恢复库存并更新状态
        for (Order order : timeoutOrders) {
            try {
                // Step 2.1: 查询订单详情
                QueryWrapper<OrderDetail> detailQueryWrapper = new QueryWrapper<>();
                detailQueryWrapper.eq("order_id", order.getId());
                List<OrderDetail> orderDetails = orderDetailMapper.selectList(detailQueryWrapper);
                // Step 2.2: 调用远程接口恢复库存
                for (OrderDetail detail : orderDetails) {
                    itemClient.deStock(detail.getItemId(), -detail.getNum()); // 负数表示增加库存
                }

                // Step 2.3: 更新订单状态为取消（5）
                order.setStatus(5);
                order.setCloseTime(new Date());
                orderMapper.updateById(order);

                log.info("订单 {} 已超时取消", order.getId());
            } catch (Exception e) {
                log.error("取消超时订单 {} 时出现异常: {}", order.getId(), e.getMessage());
                throw e; // 回滚事务
            }
        }
    }
}

